<template>
  <div v-loading="loading">
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          @click="openDailog"
        >
          添加行
        </a-button>
        <a-button @click="handleDel">
          删除行
        </a-button>
      </template>
    </div>
    <a-table
      :pagination="false"
      :columns="columns"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['coUnitName','projectName','supplyMaterial','number','contractAmount']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="record.editable">
            <a-date-picker
              v-if="col === 'pouringDate'"
              v-model="pouringDate"
              value-format="YYYY-MM-DD"
              @change="handleChange(pouringDate,record.id, col)"
            />
            <a-select
              v-else-if="col === 'calcMethodId'"
              v-model="calcMethodId"
              @change="e => handleChange(calcMethodId, record.id, col)"
            >
              <a-select-option
                v-for="item in wayArr"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select
              v-else-if="col === 'taxTypeId'"
              v-model="taxTypeId"
              @change="e => handleChange(taxTypeId, record.id, col)"
            >
              <a-select-option
                v-for="item in rateArr"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <BaseInputNumber
              v-else-if="col === 'number'"
              :precision="3"
              :value="text"
              @blur="e => handleChange(e.target.value, record.id, col)"
            />
            <BaseInput
              v-else
              :value="text"
              :disabled="col === 'calcTotle' || col === 'tax' || col === 'priceWithTax'
                || col === 'settleAmountWithoutTax' || col === 'settleTax' || col === 'settleAmountWithTax'"
              @blur="e => handleChange(e.target.value, record.id, col)"
            />
          </template>
          <template v-else>
            {{ col === 'taxTypeId' ? record.taxTypeName : col === 'calcMethodId' ? record.calcMethodName : text
            }}
          </template>
        </div>
      </template>
      <template
        slot="operation"
        slot-scope="text, record, index"
      >
        <div class="editable-row-operations">
          <span v-if="record.editable && state !== 3">
            <a @click="() => save(record.id)">保存</a>
            <a @click="cancel(record.id)">取消</a>
          </span>
          <span v-else>
            <a
              :disabled="editingKey !== ''"
              @click="() => edit(record.id)"
            >编辑</a>
          </span>
        </div>
      </template>
    </a-table>
    <!-- <pagination
            :total="totalSize"
            v-model="pageNo"
            :pageSize.sync="pageSize"
            @change="handlePageChange"
            @showSizeChange="showSizeChange"
    ></pagination> -->
  </div>
</template>
<script>
import {
  performanceList,
  performanceListDel,
  performanceAdd,
  performanceEdit
} from '@/api/material/supplier/inspection'
import { columns } from './insideModel'

const data = []
export default {
	name:'a'+Date.now(),
  props: {
    state: {
      type: Number
    },
    id: {
      type: String
    }
  },
  data() {
    this.cacheData = data.map(item => ({ ...item }))
    return {
      loading: false,
      pageNo: 1,
      pageSize: 10,
      totalSize: 0,
      selectedRowKeys: [],
      columns: columns,
      editingKey: '',
      data: [],
      optionArr: [],
      selectedId: [],
      mainTermsId: null,
      employeeName: '',
      rules: {
        coUnitName: { rule: 'required', message: '合作单位不能为空' },
        projectName: { rule: 'required', message: '工程名称不能为空' },
        supplyMaterial: { rule: 'required', message: '供应物资不能为空' },
        number: [
          { rule: 'required', message: '数量不能为空' }
        ],
        contractAmount: { rule: 'required', message: '合同金额不能为空' }
      }
    }
  },
  mounted: function() {
    if (this.state === 3) {
      this.editingKey = true
    }
    this.list()
    this.initErrMessage(this.rules)
    console.log(this.id)
    console.log(this.state)
  },
  methods: {
    openDailog: function() {
      let row = {
        coUnitName: '', projectName: '', supplyMaterial: '', number: '', contractAmount: '',
        isAdd: true, editable: true, baseId: this.id
      }
      this.data.unshift(row)
    },
    // 删除
    handleDel() {
      this.delList(performanceListDel, () => {
        this.initTable()
        this.selectedId = []
        this.selectedRowKeys = []
        this.selectedRows = []
        this.editingKey = ''
      }, { ids: this.selectedId })
    },
    initTable() {
      this.pageNo = 1
      this.list()
    },
    list() {
      this.loading = true
      let _this = this
      performanceList({ pageSize: _this.pageSize, pageNo: _this.pageNo, baseId: _this.id }).then(res => {
        if (res.code === 200) {
          _this.data = res.data
          _this.totalSize = res.totalSize
          this.cacheData = res.data.map(item => ({ ...item }))
        }
        this.loading = false
      }).catch(err => {
        this.loading = false
      })
    },
    handleChange(value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      if (target) {
        if (column === 'mainTermsStr') {
          target['mainTermsId'] = value
        } else {
          target[column] = value
        }
        if (this.rules[column]) {
          this.customValidation(value, column)
        }
        this.data = newData
      }
    },
    edit(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.mainTermsId = target.mainTermsId
        this.employeeName = target.employeeName
        this.data = newData
      }
    },
    handlePageChange(pageNo, pageSize) {
      this.pageNo = pageNo
      this.list()
      this.selectedRowKeys = []
    },
    showSizeChange(pageNo, pageSize) {
      this.pageSize = pageSize
      this.initTable()
    },
    save(key) {
      // 编辑保存
      const newData = [...this.data]
      const newCacheData = [...this.cacheData]
      const target = newData.filter(item => key === item.id)[0]
      for (let key in target) {
        if (this.rules[key]) {
          this.customValidation(target[key], key)
        }
      }
      for (let i in this.customValidationErr) {
        if (i) {
          return
        }
      }
      this.loading = true
      if (target.isAdd) {
        performanceAdd(target).then(res => {
          if (res.code === 200) {
            this.$message.success('新增成功')
            this.initTable()
          }
          this.loading = false
        })
      } else {
        target.baseId = this.id
        performanceEdit(target).then(res => {
          if (res.code === 200) {
            this.$message.success('编辑成功')
            this.initTable()
          }
          this.loading = false
        })
      }
      const targetCache = newCacheData.filter(item => key === item.id)[0]
      if (target && targetCache) {
        delete target.editable
        this.data = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedId = []
      selectedRows.map(i => {
        this.selectedId.push(i.id)
      })
      this.selectedRowKeys = selectedRowKeys
    },
    cancel(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      this.editingKey = ''
      if (target) {
        if (target.isAdd) {
          newData.splice(0, 1)
        } else {
          Object.assign(target, this.cacheData.filter(item => key === item.id)[0])
          target.editable = false
          delete target.editable
        }
        this.data = newData
      }
    }
  }
}
</script>
